#include "TCPServer.h"
#include "TCPChannel.h"
#include "util.h"
#include <cstdio>
#include "SessionHandler.h"
#include <iostream>
#include <cstdlib>
#include <set>

using namespace qy;

std::set<SessionHandler*> sessions;

void callback(SessionHandler* sh)
{
	std::set<SessionHandler*>::iterator it = sessions.find(sh);
	if(it != sessions.end())
	{
		sessions.erase(it);
	}
	delete sh;
}

int main(int argc, char *argv[])
{
	if(argc < 2)
	{
		std::cout << "Usage: " << argv[0] << " port\n";
		return -1;
	}
	TCPServer server(atoi(argv[1]));
	if(server.listen())
	{
		log_sys("Start listening at port: %d\n......", server.port());
		int sock = server.accept();
		while(sock >= 0)
		{
			SessionHandler *sh = new SessionHandler(sock, callback);
			sessions.insert(sh);
			sh->start();
			sock = server.accept();
		}
	}
	return 0;
}
